<template>
  <div class="bg-white pt">
    <Form :label-width="120" :rules="rule" ref="form" :model="form">
      <Row class="pr">
        <Col span="16">
          <FormItem label="经销商联系手机" prop="distributorMobile">
            <Input placeholder="请输入经销商联系手机" v-model="form.distributorMobile" :maxlength="60" @on-change="onInputPhoneChange"/>
          </FormItem>
        </Col>
        <Col span="2">
          <Button 
            :loading="loading" :disabled='!form.distributorMobile'
            type="primary" class="ml"
            @click="getInfoByPhone">同步经销商信息</Button>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="经销商编号" prop="distributorSn">
            <p>{{form.distributorSn}}</p>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="品牌" prop="currentBrandId">
            <RadioGroup  v-model="form.currentBrandId" @on-change='onChangeBrand'>
              <Radio :disabled="item.disabled" v-for="item in brandList" :key="item.id" :label="item.brandId">
                  <span>{{item.text}}(<span v-if="item.bind" class="font-blue">已签约</span><span v-else>未签约</span>)</span>
              </Radio>
            </RadioGroup >
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="是否覆盖签约信息" prop='isfg'>
             <RadioGroup  v-model="form.isfg">
              <Radio :label="true"><span>是</span></Radio>
              <Radio :label="false" v-show="false"><span>否</span></Radio>
             </RadioGroup>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="是否短信通知">
            <Checkbox v-model="form.isMessageNotification"></Checkbox>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr" v-show="form.domianPrefix">
        <Col span="20">
          <FormItem label="经销商登录地址" prop="domianPrefix">
            <span id="jxsDomianPrefix">{{form.domianPrefix}}</span>
            <Button size='small' icon='md-copy' data-clipboard-action="copy" :data-clipboard-text="form.domianPrefix" data-clipboard-target="#jxsDomianPrefix" class="copyBtn"  @click="copyUrl">复制</Button>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="经销商签约名称" prop="distributorContractName">
            <Input placeholder="经销商签约名称" :disabled="true"  v-model="form.distributorContractName" :maxlength="60"/>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="经销商联系人" prop="distributorContact">
            <Input placeholder="经销商联系人" v-model="form.distributorContact" :maxlength="60"/>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="地址选择" prop="areaId">
            <!-- 同一页面获取一次数据 -->
            <AreaSelect @input="onChangeArea" v-model="value"></AreaSelect>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="详细地址" prop="address">
            <Input class="mt" placeholder="详细地址" type="textarea" v-model="form.address" :maxlength="60"/>
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="法人身份证正面" prop='idCardPositivePic'>
            <PictureEditItem
              :uploadList = "form.cardz"
              :maxlength = "1"
              :large="true"
              @uploadPic="uploadPic($event, 'idCardPositivePic')"
            />
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="法人身份证反面" prop='idCardNegativePic'>
            <PictureEditItem
              :uploadList = "form.cardf"
              :maxlength = "1"
              :large="true"
              @uploadPic="uploadPic($event, 'idCardNegativePic')"
            />
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem label="营业执照" prop='businessLicensePic'>
            <PictureEditItem
              :uploadList = "form.yyzz"
              :maxlength = "1"
              :large="true"
              @uploadPic="uploadPic($event, 'businessLicensePic')"
            />
          </FormItem>
        </Col>
      </Row>
      <Row class="pr">
        <Col span="20">
          <FormItem class="flex-column-end" label="业务区域" prop='areaDTOList'>
            <AreaTree
              ref="treeadd"
              class="mb"
              :checkedIdList="form.checkedIdList"
              @onCheckChange="onCheckChange"
              customerClass="treeplc"
            />
          </FormItem>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
  import AreaSelect from '@/components/AreaSelect';
  import AreaTree from '@/components/AreaTree';
  import ImageListUpload from '@/components/ImageListUpload';
  import PictureEditItem from "~/PictureEditItem";
  import DepartmentRadio from "~/DepartmentRadio";
  import { mapState, mapGetters } from 'vuex'
  import { getValueArray, setEmptyArray, setArrayValue} from '@/views/sales/common/TableSaleMethods'
  export default {
    props: {
      form: {
        type: Object
      },
      brandList: {
        type: Array,
        default: () => []
      }
    },
    components: {
      AreaSelect,
      AreaTree,
      ImageListUpload,
      PictureEditItem,
      DepartmentRadio
    },
    mounted () {
      this.$bus.$on('onSendData', this.setList)
    },
    data() {
      return {
        rule: {
          'distributorMobile': [{ required: true, message: '请输入11位手机号码', trigger: 'blur', pattern: /^1[0-9]{10}$/ }],
          'distributorContractName': [{ required: true, message: '请输入经销商签约名称', trigger: 'blur' }],
          'distributorContact': [{ required: true, message: '请输入经销商联系人名称', trigger: 'blur' }],
          'areaId': [{ required: true, message: '请输入选择省市区', trigger: 'blur' }],
          'bindDepartmentId': [{ required: true, message: '请输入业务部门', trigger: 'blur' }],
          'areaDTOList': [{ required: true, type: 'array', message: '请选择业务区域', trigger: 'change' }]
        },
        loading: false
      }
    },
    methods: {
      // valArea (rule, value, callback) {
      //   debugger
      //   callback()
      // },
      validateForm () {
        return new Promise((resolve, reject) => {
          this.$refs.form.validate(valid => {
            resolve(valid)
          })
        })
      },
      onInputPhoneChange() {
        const { distributorMobile, distributorSn } = this.form
        let reg = /^1[0-9]{10}$/
        if(!reg.test(distributorMobile)) {
          this.$emit('formDataByPhone', { distributorContractDTO: null, distributorDTO: {} })
          return
        }
      },
      getInfoByPhone() {
        const { distributorMobile } = this.form
        let reg = /^1[0-9]{10}$/
        if(!reg.test(distributorMobile)) return
        this.getInfo(distributorMobile)
      },
      getInfo(distributorMobile) {
        this.loading = true
        this.$ajaxGet(`/distributor/contract/findByPhone/${distributorMobile}`, { phone: distributorMobile }).then(res => {
          this.loading = false
          this.$emit('formDataByPhone', res)
        }).catch(err => {
          console.error(err)
          this.loading = false
        })
      },
      onCheckChange(val, x, y) {
        if (!x.length) {
          this.form.areaDTOList = []
          return
        }
        this.getTreeParams(x[0].children)
        let arr = val.filter(e => {
          return e.children && !e.children.length && e.checked
        }).map(e => {
          return  { areaId: e.id, areaName: e.name }
        })
        // this.form.areaDTOList = arr
      },
      // getTreeParams
      getTreeParams(data) {
        // 拿到树的数据和选中的比较 - 有的的化就把
        // checked = true isAllSelect = true 
        // indeterminate = false 删掉
        let data1 = JSON.parse(JSON.stringify(data))
        let loop = (data, val) => {
          for (let key in data) {
            if( !data[key][val.index] && !data[key].checked) {
                data[key] = ''
            }
            if (data[key].checked) {
              data[key].isAllSelect = true
            } else {
              if (data[key]) data[key].isAllSelect = false
            }
            if (data[key][val.childName] && data[key][val.childName].length) {
                loop(data[key][val.childName], val)
            }
          }
        }
        loop(data1, {index: 'indeterminate',childName: "children"})
        setEmptyArray(data1, {index: 'indeterminate',childName: "children"})
        this.form.areaDTOList = data1
      },
      getAreaList(data1) {
        let loop = (data) => {
          data.forEach((item, index) => {
            delete item.indeterminate
            if(item.children.length) {
              loop(item.children)
            }
          })
        }
        loop(data1)
      },
      onChangeArea(val, or) {
        let [province={}, city={}, area={}] = or; // 省 市 区
        this.form.provinceId = province.id
        this.form.provinceName = province.name
        this.form.cityId = city.id
        this.form.cityName = city.name
        this.form.areaId = area.id
        this.form.areaName = area.name
      },
      uploadPic(pl, type) {
        let img = pl.map(item => item.imgUrl).join(',')
        this.form[type] = img
      },
      onChangeDepart(val) {
        this.form.bindDepartmentId = val
      },
      onChangeBrand(val) {
        let item = this.brandList.find(item => item.brandId === val)
        const { brandId, brandName } = item
        this.form.currentDistributorBrandDTO = { brandId, brandName }
        this.$emit('changeBrand', item)
      },
      copyUrl() {
        let clipboard = new this.$clipboard('.copyBtn')
        clipboard.on('success', e => {
          this.$Message.success('复制成功')
          clipboard.destroy() //使用destroy可以清除缓存
        })
        clipboard.on('error',e => {
          this.$Message.error('复制失败，请手动复制')
          clipboard.destroy()
        })
      },
      setList() {
        // 基础数据的地区没数据
        // delete this.dealer.basicForm.areaDTOList
        // delete this.dealer.basicForm.idCardPositivePic
        // delete this.dealer.basicForm.idCardNegativePic
        // delete this.dealer.basicForm.businessLicensePic
        this.form = Object.assign(this.form, this.dealer.basicForm)
        this.form.checkedIdList = (this.dealer.basicForm.resultAreaDTOList || []).map(item => item.areaId)
        // 如果图片为空就显示添加
        this.form.cardz = this.form.idCardPositivePic ? [{status: 'finished', imgUrl: this.form.idCardPositivePic}] : []
        this.form.cardf = this.form.idCardNegativePic ? [{status: 'finished', imgUrl: this.form.idCardNegativePic}] : []
        this.form.yyzz = this.form.businessLicensePic ? [{status: 'finished', imgUrl: this.form.businessLicensePic}] : []
        if (this.form.cardz.length && !this.form.cardz[0].imgUrl) this.form.cardz = []
        if (this.form.cardf.length && !this.form.cardf[0].imgUrl) this.form.cardf = []
        if (this.form.yyzz.length && !this.form.yyzz[0].imgUrl) this.form.yyzz = []
        this.form.distributorMobile = this.form.contactMobile
        this.form.distributorSn = this.form.sn
        this.form.distributorContractName = this.form.contactName
        this.form.businessLicensePic = this.form.businessLicenseUrl
        if (this.$route.query.distributorId) this.form.distributorId = this.$route.query.distributorId
        this.form.id = ''
        this.brandList = this.brandList.map(item => {
          if (this.dealer.brandDtos.find(i => i.brandName===item.brandName&&i.bind)) {
            item.bind = true
            item.disabled = true
          } else {
            item.disabled = false
          }
          return item
        })
      }
    },
    computed: {
      value: {
        get() {
          const { provinceId='', cityId='', areaId='' } = this.form
          let val = []
          if(provinceId) {
            val = [provinceId, cityId, areaId]
          }
          return val
        },
        set(newval) {
          const [ provinceId, cityId, areaId ] = newval
          
          this.form = Object.assign(this.form, {provinceId, cityId, areaId})
        }
      },
      ...mapState([
      'dealer'
      ])
    },
    watch: {
      // 'form.areaDTOList'(val) {

      // }
    }
  }
</script>
